package com.yexiao.cofe.interceptor;

import com.yexiao.cofe.common.annotation.PermissionController;
import com.yexiao.cofe.common.exception.BusinessException;
import com.yexiao.cofe.util.SystemUtil;
import com.yexiao.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author lkl
 * @since 2025/4/8
 */
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();

            // debug让行
            String debug = request.getHeader("debug");
            if(StrUtil.isNotEmpty(debug)) {
                return true;
            }

            PermissionController permissionController = method.getAnnotation(PermissionController.class);
            if(permissionController == null){
                // 没加注解，放行
                return true;
            }

            String[] value = permissionController.value();
            if(value.length == 0) {
                // 没设置权限，放行
                return true;
            }

            // 获取token
            String token = request.getHeader("Authorization");
            if(StrUtil.isEmpty(token)) {
                log.warn("权限拦截器拦截, 【原因】: 没有token");
                throw new BusinessException("token缺失");
            }

            // 兼容待Bearer的情况
            if(token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            List<String> permissionList = SystemUtil.listUserPermission(token);
            for (String s : value) {
                if(!permissionList.contains(s)) {
                    throw new BusinessException("无权限: " + s);
                }
            }
            return true;
        }

        return true;
    }
}
